package com.zzw.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class FutureTaskForMultiCompute {

	public static void main(String[] args) {
		FutureTaskForMultiCompute task = new FutureTaskForMultiCompute();
		List<FutureTask<Integer>> taskList = new ArrayList<FutureTask<Integer>>();
		ExecutorService exec = Executors.newFixedThreadPool(5);
		for(int i = 0;i < 5;i++){
			FutureTask<Integer> ft = new FutureTask<>(task.new ComputeTask(i, ""+i));
			taskList.add(ft);
			exec.submit(ft);
		}
		System.out.println("提交结束");
		Integer totaoResult = 0;
		for(FutureTask<Integer> ft:taskList){
			try {
				totaoResult = totaoResult + ft.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		exec.shutdown();
		System.out.println("result:" + totaoResult);
	}
	
	
	 private class ComputeTask implements Callable<Integer> {  
		  
	        private Integer result = 0;  
	        private String taskName = "";  
	          
	        public ComputeTask(Integer iniResult, String taskName){  
	            result = iniResult;  
	            this.taskName = taskName;  
	            System.out.println("生成子线程计算任务: "+taskName);  
	        }  
	          
	        public String getTaskName(){  
	            return this.taskName;  
	        }  
	          
	        @Override
			public Integer call() throws Exception {
	            for (int i = 0; i < 100; i++) {  
	                result =+ i;  
	            }  
	            // 休眠5秒钟，观察主线程行为，预期的结果是主线程会继续执行，到要取得FutureTask的结果是等待直至完成。  
	            Thread.sleep(5000);  
	            System.out.println("子线程计算任务: "+taskName+" 执行完成!" + "结果:" + result);  
	            return result;  
	        }  
	    }  
}
